﻿using AutoMapper;
using BW.MesProject.Public.Application.Dto.Input;
using BW.MesProject.Public.Application.Dto.Output;
using BW.MesProject.Public.Application.Helper;
using BW.MesProject.Public.Domain.RBAC;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using BW.MesProject.WareHouse.Domain;
using Dm;
using MD5Hash;
using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace BW.MesProject.Public.Application
{
    /// <summary>
    /// 用户服务实现
    /// </summary>
    public class UserServices : IUserServices
    {
        private readonly IBaseRepository<UserModel> _userRepository;
        private readonly IMapper _mapper;
        private readonly IJwtService _jwtService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="UserRepository"></param>
        /// <param name="mapper"></param>
        public UserServices(IBaseRepository<UserModel> UserRepository, IMapper mapper, IJwtService jwtService)
        {
            _userRepository = UserRepository;
            this._mapper = mapper;
            this._jwtService = jwtService;
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiResult<UserLoginOutput> UserLogin(UserLoginInput input)
        {
            //判断用户名称和密码是否为空
            if (string.IsNullOrEmpty(input.UserName) || string.IsNullOrEmpty(input.Password))
            {
                return new ApiResult<UserLoginOutput>()
                {
                    Code = ApiEnums.Fail,
                    Message = "用户名称和密码不能为空"
                };
            }
            try
            {
                ////密码加密Md5
                //var pwd = input.Password.GetMD5();
                ////根据用户名称和密码获取用户信息
                //var userModel = _userRepository.GetAll().First(x => x.UserId == input.UserName && x.Password == pwd);
                ////判断用户是否存在
                //if (userModel == null)
                //{
                //    return new ApiResult<UserLoginOutput>
                //    {
                //        Code = ApiEnums.Fail,
                //        Message = "用户不存在或密码错误",
                //        Data = null
                //    };
                //}
                //密码加密Md5
                var pwd = PasswordHelper.AesEncrypt(input.Password);
                //根据用户名称和密码获取用户信息
                var userModel = _userRepository.GetAll().Where(x => x.UserId == input.UserName && x.Password == pwd && x.IsEnable==true);
                //判断用户是否存在
                if (userModel == null)
                {
                    return new ApiResult<UserLoginOutput>
                    {
                        Code = ApiEnums.Fail,
                        Message = "用户不存在或密码错误",
                        Data = null
                    };
                }
                //链表查询
                var query1 = userModel.LeftJoin<JobModel>((a, b) => a.JobCode == b.JobId).LeftJoin<DEPModel>((a, b, c) => a.DepCode == c.DepId).Select((a, b, c) =>
                    new UserLoginOutput
                    {
                        UserId = a.UserId,
                        UserName = a.UserName,
                        UserEmail = a.UserEmail,
                        Password=a.Password,
                        RealName=a.RealName,
                        IdCard = a.IdCard,
                        Phone = a.Phone,
                        JobCode = a.JobCode,
                        JobName = b.JobName,
                        DepCode = a.DepCode,
                        DepName = c.DepName
                    });

                //var data = _mapper.Map<UserLoginOutput>(query1);
                var data = query1?.ToList();
                if (data != null)
                {
                    // 生成JWT令牌
                    string token = _jwtService.GenerateToken(
                        data[0].UserId,
                        data[0].UserName,
                        data[0].RealName);

                    // 将令牌设置到输出对象
                    data[0].Token = token;

                    return new ApiResult<UserLoginOutput>
                    {
                        Code = ApiEnums.Success,
                        Message = "登录成功",
                        Data = data[0]
                    };
                }
                else
                {
                    return new ApiResult<UserLoginOutput>
                    {
                        Code = ApiEnums.Success,
                        Message = "登录失败",
                        Data = null
                    };
                }
               
            }
            catch (Exception ex)
            {
                return new ApiResult<UserLoginOutput>
                {
                    Code = ApiEnums.Error,
                    Message = $"登录失败: {ex.Message}",
                    Data = null
                };
            }
        }


        /// <summary>
        /// 查询人员
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="pagesize"></param>
        /// <param name="pageNum"></param>
        /// <param name="DepId"></param>
        /// <returns></returns>
        public ApiResult<List<UserLoginOutput>> GetUser(string? UserName, int pagesize, int pageNum, string DepId)
        {
            try
            {
                int totalCount = 0;
                //查询名称来显示数据
                var list = _userRepository.GetAll().Where(x => x.JobCode != null);
                
                var query = list
                    .LeftJoin<JobModel>((a, b) => a.JobCode == b.JobId)
                    .LeftJoin<DEPModel>((a, b, c) => a.DepCode == c.DepId)
                    .Where(a => a.DepCode == DepId && a.IsEnable == true);
                
                // 按名称筛选
                if (!string.IsNullOrEmpty(UserName))
                {
                    query = query.Where(a => a.UserName.Contains(UserName));
                }
                
                // 排序
                query = query.OrderBy(a => new { a.CreatedTime, a.UserId });
                
                // 映射到UserLoginOutput
                var mappedQuery = query.Select((a, b, c) =>
                    new UserLoginOutput
                    {
                        UserId = a.UserId,
                        UserName = a.UserName,
                        UserEmail = a.UserEmail,
                        Password = a.Password,
                        RealName = a.RealName,
                        IdCard = a.IdCard,
                        Phone = a.Phone,
                        JobCode = a.JobCode,
                        JobName = b.JobName,
                        DepCode = a.DepCode,
                        DepName = c.DepName
                    });
                
                // 结果列表
                List<UserLoginOutput> queryList;
                
                // 分页处理
                if (pagesize > 0)
                {
                    queryList = mappedQuery.ToPageList(pageNum, pagesize, ref totalCount);
                }
                else
                {
                    queryList = mappedQuery.ToList();
                    totalCount = queryList.Count;
                }

                return new ApiResult<List<UserLoginOutput>>()
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = queryList,
                    TotalCount = totalCount,
                    PageNum = pageNum,
                    PageSize = pagesize
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查询人员信息时发生异常: {ex.Message}");
                return new ApiResult<List<UserLoginOutput>>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"查询失败: {ex.Message}",
                    Data = new List<UserLoginOutput>(),
                    TotalCount = 0,
                    PageNum = pageNum,
                    PageSize = pagesize
                };
            }
        }


        /// <summary>
        /// 查询人员新
        /// </summary>
        /// <param name="qryInput"></param>
        /// <returns></returns>
        public ApiResult<List<EMPOut>> GetUserNew(QryInput qryInput)
        {
            try
            {
                int totalCount = 0;

                // 获取所有库位
                var list = _userRepository.GetAll();


                if (qryInput.PageSize == 0)
                {

                    list = list.OrderBy(u => u.CreatedTime);
                }
                else
                {

                    // 按编码查询
                    if (!string.IsNullOrEmpty(qryInput.QryID) && !string.IsNullOrEmpty(qryInput.QryName))
                    {
                        list = list.Where(x => x.UserId.Contains(qryInput.QryID) && x.UserName.Contains(qryInput.QryName));
                    }
                    else if (!string.IsNullOrEmpty(qryInput.QryID))
                    {
                        list = list.Where(x => x.UserId.Contains(qryInput.QryID));
                    }
                    else if (!string.IsNullOrEmpty(qryInput.QryName))
                    {
                        list = list.Where(x => x.UserName.Contains(qryInput.QryName));
                    }


                }
                // 处理结果数据
                var result = new List<EMPOut>();

                //链表查询
                var query1 = list.LeftJoin<JobModel>((a, b) => a.JobCode == b.JobId).LeftJoin<DEPModel>((a, b, c) => a.DepCode == c.DepId).Select((a, b, c) =>
                    new EMPOut
                    {
                        UserId = a.UserId,
                        UserName = a.UserName,
                        UserEmail = a.UserEmail,
                        PassWord=a.Password,
                        IdCard = a.IdCard,
                        Phone = a.Phone,
                        CreatedTime = a.CreatedTime,
                        UpdatedTime = a.UpdatedTime,
                        IsDeleted = a.IsDeleted,
                        IsEnable = a.IsEnable,
                        CreatedBy = a.CreatedBy,
                        JobCode = a.JobCode,
                        JobName = b.JobName,
                        DepCode = a.DepCode,
                        DepName = c.DepName
                    });

                //获取集合
                var queryList = query1?.ToList();


                // 分页处理
                if (qryInput.PageSize > 0)
                {
                    queryList = queryList
                        .OrderByDescending(x => x.CreatedTime)
                        .Skip((qryInput.PageNum - 1) * qryInput.PageSize)
                        .Take(qryInput.PageSize)
                        .ToList();
                }

                return new ApiResult<List<EMPOut>>()
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = queryList,
                    TotalCount = query1.ToList().Count,
                    PageNum = qryInput.PageNum,
                    PageSize = qryInput.PageSize
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查询人员信息时发生异常: {ex.Message}");
                return new ApiResult<List<EMPOut>>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"查询失败: {ex.Message}",
                    Data = new List<EMPOut>(),
                    TotalCount = 0,
                    PageNum = qryInput.PageNum,
                    PageSize = qryInput.PageSize
                };
            }

        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="EMP"></param>
        /// <returns></returns>
        public ApiResult<int> AddUser(UserModel User)
        {
            try
            {
                //判断人员编码，名称是否为空
                if (string.IsNullOrEmpty(User.UserId) || string.IsNullOrEmpty(User.UserName) || string.IsNullOrEmpty(User.Password))
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "请检查人员编码，名称是否为空"
                    };
                }
                var model = _userRepository.GetValue(x => x.UserId == User.UserId);
                if (model != null && !string.IsNullOrEmpty(model.UserId))
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "人员编号重复，请重新检查修改！！！"
                    };
                }
                //密码加密Md5
                //var pwd = User.Password.GetMD5();
                //model.Password = pwd;
                //添加
                var models = _mapper.Map<UserModel>(User);

                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Message = "添加成功",
                    Data = _userRepository.Add(User),
                    TotalCount = 0
                };
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"添加人员时发生异常: {ex.Message}");

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"添加失败: {ex.Message}",
                    Data = 0,
                    TotalCount = 0
                };
            }
        }


        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateUser(UserModel model)
        {
            try
            {
                //根据id查询是否有这条数据没有就修改不了
                var query = _userRepository.GetValue(x => x.UserId == model.UserId);
                if (query == null)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "修改失败，未找到指定的人员信息",
                        Data = 0,
                        TotalCount = 0
                    };
                }

                //保存添加人和添加时间，添加修改人和修改时间
                _userRepository.Update(model);

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "修改成功",
                    Data = 1,
                    TotalCount = 0
                };
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"修改人员信息时发生异常: {ex.Message}");

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"修改失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 修改启用
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateEnable(UserModel model)
        {
            var IsEnable = model.IsEnable;
            //根据id修改逻辑删除为 false
            model = _userRepository.GetValue(x => x.UserId == model.UserId);
            model.IsEnable = IsEnable;
            var Message = string.Empty;
            if (IsEnable)
            {
                Message = "启用成功";
            }
            else
            {
                Message = "停用成功";
            }
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = Message,
                Data = _userRepository.Update(model),
                TotalCount = 0
            };

        }

        /// <summary>
        /// 软删除（修改状态）
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateDelete(string Id)
        {
            //根据id修改逻辑删除为 false
            var model = _userRepository.GetValue(x => x.UserId == Id);
            model.IsDeleted = true;
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "删除成功",
                Data = _userRepository.Update(model),
                TotalCount = 0
            };
        }

        /// <summary>
        /// 查询表是否有该编码
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public ApiResult<int> GetUserId(string UserId)
        {
            var model = _userRepository.GetValue(x => x.UserId == UserId);
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "成功",
                Data = 1,
                TotalCount = 0
            };

        }
    }
}
